package com.halflife.comeElectricity.user;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jsms.api.SendSMSResult;
import cn.jsms.api.ValidSMSResult;
import cn.jsms.api.common.SMSClient;
import cn.jsms.api.common.model.SMSPayload;
import com.halflife.framework.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by liuj3 on 2018/2/6
 */

@RestController
@RequestMapping("mc_login")
public class UserController {

    private Logger log = LoggerFactory.getLogger(UserController.class);
    @Resource
    private UserRepository userRepositroy;


    @GetMapping("/{id}")
    public User getUser(@PathVariable Integer id) {

        return userRepositroy.selectByPrimaryKey(id);
    }

    @GetMapping("/login/reg/{name}")
    public List<User> getUserByUserName(@PathVariable String name) {

        return userRepositroy.selectByUserName(name);
    }

    @GetMapping("")
    public List<User> getAllUsers() {
        return userRepositroy.selectAll();
    }

    @PostMapping("")
    public ResponseEntity addUser(@RequestBody User merchant, HttpServletRequest request) {
//        merchant.setValid(Boolean.TRUE);
//        merchant.setPhone(merchant.getPhone());
//        Integer id = userRepositroy.insert(merchant);
        return new ResponseEntity(merchant, HttpStatus.OK);
    }

    @PutMapping("")
    public ResponseEntity updateUser(@RequestBody User merchant, HttpServletRequest request) {
        Integer id = userRepositroy.updateByPrimaryKey(merchant);
        return new ResponseEntity(merchant, HttpStatus.OK);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity updateUser(@PathVariable Integer id, HttpServletRequest request) {
        Integer key = userRepositroy.deleteByPrimaryKey(id);
        return new ResponseEntity(key, HttpStatus.OK);
    }

    @Value("${system.jsms.appkey}")
    private String appkey;
    @Value("${system.jsms.masterSecret}")
    private String masterSecret;

    /**
     * 获取极光短信验证码
     * @param phone
     * @param request
     * @return
     */
    @GetMapping("/getGJCode/{phone}")
    public ResponseEntity getJGCode(@PathVariable String phone, HttpServletRequest request){
        Map map = new HashMap();
        try {
            SMSClient client = new SMSClient(masterSecret,appkey);
            SMSPayload payload
                    = SMSPayload.newBuilder()
                    .setMobileNumber(phone)
                    .setTempId(1)
                    .build();
            SendSMSResult res = client.sendSMSCode(payload);
            log.info(res.toString());
            return new ResponseEntity<SendSMSResult>(res, HttpStatus.OK);
        } catch (BusinessException e) {

            return new ResponseEntity(e.toString(), HttpStatus.CONFLICT);
        }catch (APIConnectionException e) {

            log.error("服务器连接错误,稍后再试!", e);
            return new  ResponseEntity(e, HttpStatus.INTERNAL_SERVER_ERROR);
        } catch (APIRequestException e) {

            log.error("系统异常,请求错误!", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Message: " + e.getMessage());
            return new ResponseEntity(e, HttpStatus.CONFLICT);
        }
        //return new ResponseEntity<SendSMSResult>(res, HttpStatus.OK);
    }

    /**
     * 验证极光短信验证码
     * @param msgId
     * @param code
     * @param request
     * @return
     */
    @GetMapping("/validGJCode")
    @ResponseStatus(HttpStatus.CREATED)
    public ResponseEntity validGJCode(@RequestParam(value="msgId", required = false) String msgId,
                                      @RequestParam(value="code", required = false) String code,
                                      HttpServletRequest request){
        try{
            SMSClient client = new SMSClient(masterSecret,appkey);
            //验证验证码
            ValidSMSResult res = client.sendValidSMSCode(msgId, code);
            return new ResponseEntity<ValidSMSResult>(res, HttpStatus.OK);

        } catch (BusinessException e) {

            return new ResponseEntity(e.toString(), HttpStatus.CONFLICT);
        }catch (APIConnectionException e) {

            log.error("服务器连接错误,稍后再试!", e);
            return new  ResponseEntity(e.toString(), HttpStatus.INTERNAL_SERVER_ERROR);
        } catch (APIRequestException e) {

            log.error("系统异常,请求错误!", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Message: " + e.getMessage());
            // return new ResponseEntity(e.toString(), HttpStatus.CONFLICT);
            return new ResponseEntity(e, HttpStatus.CONFLICT);
        }
    }
}
